package com.hmdp.service.impl;

import ch.qos.logback.classic.spi.STEUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Autowired
    private IFollowService followService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据指定id查询博客内容
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if(blog==null){
            Result.fail("用户不存在");
        }
        queryBlogUser(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }
    /**
     * 查询热门博客
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }
    /**
     * 给某一博客点赞,刚开始使用Set集合，后面使用ZSet集合
     * id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //1.获取当前用户登录id
        Long userId = UserHolder.getUser().getId();
        //2.判断当前用户有没有给博客点过赞
        String key=BLOG_LIKED_KEY+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        if(score==null){
        //if(BooleanUtil.isFalse(isMember)){
            //如果没有点过赞，数据库加一，保存用户到redis的set集合
            boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            if(isSuccess) {
                //stringRedisTemplate.opsForSet().add(key, userId.toString());
                stringRedisTemplate.opsForZSet().add(key, userId.toString(),System.currentTimeMillis());
            }
        }else{
            //如果点过赞，再次点赞，数据库减一，剔除用户到redis的set集合
            boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            if(isSuccess) {
                //stringRedisTemplate.opsForSet().remove(key, userId.toString());
                stringRedisTemplate.opsForZSet().remove(key, userId.toString(),System.currentTimeMillis());
            }
        }
        return Result.ok();
    }
    /**
     * 根据指定博客id查询当前博客下点赞的人
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String key=BLOG_LIKED_KEY+id;
        //1.查询top5的点赞用户
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(range==null||range.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //2.通过用户id查询数据
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        //3.根据用户id集合查询用户
        //List<User> users = userService.listByIds(ids);
        List<User> users = userService.query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        //4.返回的是UserDTO类型的数据
        List<UserDTO> userDTOS = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
    /**
     * 发布blog,同时推送到粉丝收件箱
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        //1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2.保存探店blog
        boolean isSuccess = save(blog);
        //3.保存blog成功之后推送到粉丝收件箱
        if(!isSuccess){
            return Result.ok("新增笔记失败！");
        }
        //3.1查询blog作者的所有粉丝，在tb_follow表中找到所有与userId(当前作者)相同的follow_user_id
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        //3.2遍历所有粉丝，获取粉丝的id,推送新增笔记的id
        for(Follow follow:follows) {
            Long userId = follow.getId();
            String key=FEED_KEY+userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        //4.返回id
        return Result.ok(blog.getId());
    }
    /**
     * 使用redis的Zset集合实现不重复查询的滚动分页
     * @param max 本次查询的最大时间，上一次查询的最小时间
     * @param offset 偏移量，上次查询最小时间戳的个数
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //查询收件箱里的所有笔记做滚动分页查询
        //1.获取当前用户，找到收件箱
        Long userId = UserHolder.getUser().getId();
        String key=FEED_KEY+userId;
        //2.滚动分页查询收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.收件箱为空
        if(typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        //4.收件箱不为空，解析数据
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime=0;
        int os=1;//最小时间的个数
        for(ZSetOperations.TypedTuple<String> tuple:typedTuples){
            //获取blogId
            String idstr = tuple.getValue();
            ids.add(Long.valueOf(idstr));
            //获取score,转成long型
            long time = tuple.getScore().longValue();
            if(time==minTime){
                os++;
            }else{
                minTime=time;
                os=1;
            }
        }
        //5.根据id批量查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        //还需查询blog关联的用户信息，blog的点赞信息
        for(Blog blog:blogs){
            queryBlogUser(blog);
            isBlogLiked(blog);
        }
        //6.封装成前端要的数据格式
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }

    /**
     * 查询用户功能
     * @param blog
     */
    private void queryBlogUser(Blog blog) {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
    }

    /**
     * 查询当前用户给博客的点赞情况
     * @param blog
     */
    private void isBlogLiked(Blog blog){
        //获取当前用户登录id
        UserDTO user = UserHolder.getUser();
        if(user==null){
            //用户未登录，无需查询是否点赞
            return;
        }
        Long userId = UserHolder.getUser().getId();
        String key=BLOG_LIKED_KEY+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
        //判断当前用户有没有点过赞
        //Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        //给blog的isliked字段赋值
        //blog.setIsLike(BooleanUtil.isTrue(isMember));

    }
}
